const app = getApp();

Page({
  data: {
    remark: {},
    isLoaded: false,
  },
  onLoad(options) {
    wx.showLoading({
      title: '加载中',
    })
    wx.setNavigationBarTitle({ title: '客户备注' });
    const { openid } = options;
    this.setData({
      openid,
    }, () => this.getRemarkDetail());
  },

  onInput(e){
    let { key } = e.currentTarget.dataset;
    let { remark } = this.data;
    remark[key] = e.detail.value;
    this.setData({
      remark
    })
  },

  getRemarkDetail() {
    app.util.request({
      url: 'card/api/getRemarkDetail',
      data: {
        m_openid: this.data.openid,
      },
      showLoading: true,
      success: res => {
        if (res.data && res.data.errno === 0) {
          this.setData({
            remark: res.data.data,
          });
        }
      },
      complete: () => {
        this.setData({
          isLoaded: true
        })
      }
    });
  },

  formSubmit(e) {
    const value = e.detail.value;
    if (!value.mobile || !value.mobile.trim()) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
      });
      return false;
    } else {
      const exp = app.util.phoneExp.mobile;
      if (!exp.test(value.mobile)) {
        wx.showToast({ title: '手机号格式错误', icon: 'none' });
        return false;
      }
    }

    if (value.email){
      const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
      if (!myReg.test(value.email)) {
        wx.showToast({ title: '邮箱格式错误', icon: 'none' });
        return false;
      }
    }

    app.util.request({
      url: 'card/api/editRemark',
      data: {
        m_openid: this.data.openid,
        ...value,
      },
      success: res => {
        if (res.data && res.data.errno === 0) {
          wx.showToast({
            title: '备注编辑成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              setTimeout(() => wx.navigateBack({ delta: 1 }), 2000);
            },
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.message || '备注编辑失败',
          });
        }
      },
    });
  },
});
